<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--分类数据-->
      <el-col :span="3" :xs="24">
        <div class="head-container">
          <el-input
              v-model="categoryName"
              clearable
              placeholder="请输入分类名称"
              prefix-icon="Search"
              style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
              :data="categoryList"
              :expand-on-click-node="false"
              :filter-node-method="filterNode"
              ref="categoryTreeRef"
              :props="treeProps"
              highlight-current
              node-key="id"
              @node-click="handleNodeClick"
              accordion
          />
        </div>
      </el-col>

      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="题目名称" prop="name">
            <el-input
                v-model="queryParams.name"
                placeholder="请输入题干"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="题目类型" prop="type" style="width: 300px">
            <el-select v-model="queryParams.type" placeholder="请选择题目类型" clearable>
              <el-option
                  v-for="dict in question_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="难易度" prop="difficulty" style="width: 300px">
            <el-select v-model="queryParams.difficulty" placeholder="请选择难易度" clearable>
              <el-option
                  v-for="dict in question_difficulty"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['exam:question:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                plain
                icon="Edit"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['exam:question:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                plain
                icon="Delete"
                :disabled="multiple"
                @click="handleDelete"
                v-hasPermi="['exam:question:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="info"
                plain
                icon="Upload"
                @click="handleImport"
                v-hasPermi="['exam:question:import']"
            >导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                plain
                icon="Download"
                @click="handleExport"
                v-hasPermi="['exam:question:export']"
            >导出
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="questionList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center"/>
          <el-table-column label="题目id" align="center" prop="id" v-if="false"/>
          <el-table-column label="题目名称" align="center" prop="name" width="400px"/>
          <el-table-column label="题目类型" align="center" prop="type">
            <template #default="scope">
              <dict-tag :options="question_type" :value="scope.row.type"/>
            </template>
          </el-table-column>
          <el-table-column label="课程分类" align="center" prop="cateName3"/>
          <el-table-column label="难易度" align="center" prop="difficulty">
            <template #default="scope">
              <dict-tag :options="question_difficulty" :value="scope.row.difficulty"/>
            </template>
          </el-table-column>
          <el-table-column label="回答次数" align="center" prop="answerTimes" sortable/>
          <el-table-column label="分值" align="center" prop="score"/>
          <el-table-column label="更新时间" align="center" prop="updateTime" width="180" sortable>
            <template #default="scope">
              <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新人" align="center" prop="updateBy"/>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150px"
                           fixed="right">
            <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['exam:question:edit']">修改
              </el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['exam:question:remove']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
        />
      </el-col>
    </el-row>
    <!-- 添加或修改题目对话框 -->
    <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
      <el-form ref="questionRef" :model="form" :rules="rules" label-width="100px">
        <!--        <el-form-item label="机构id" prop="insId">-->
        <!--          <el-input v-model="form.insId" placeholder="请输入机构id"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="题目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入题干"/>
        </el-form-item>
        <el-form-item label="题目类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio
                v-for="dict in question_type"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="选择题选项" prop="options" v-if="form.type === 1 || form.type === 2">
          <div v-for="(option, index) in form.options" :key="index" class="option-row">
            <!-- 生成字母标签，如A、B、C等 -->
            <span class="letter-label">{{ getLetter(index) }}.</span>
            <el-input
                v-model="form.options[index]"
                placeholder="请输入选项"
                style="width: 80%; margin-left: 10px;"
                class="options-input"
            />
          </div>
          <!-- 添加选项按钮 -->
          <el-button type="primary" icon="Plus" @click="addOption">添加选项</el-button>
          <!-- 删除选项按钮 -->
          <el-button type="danger" icon="Delete" @click="deleteOption">删除选项</el-button>
        </el-form-item>
        <el-form-item label="正确答案" prop="answer">
          <!-- 根据题目类型显示不同的输入框 -->
<!--          <div v-if="form.type === 1">-->
<!--            <el-radio-group v-model="form.answer">-->
<!--              <el-radio label="1">A</el-radio>-->
<!--              <el-radio label="2">B</el-radio>-->
<!--              <el-radio label="3">C</el-radio>-->
<!--              <el-radio label="4">D</el-radio>-->
<!--            </el-radio-group>-->
<!--          </div>-->
<!--          <div v-if="form.type === 2">-->
<!--            <el-checkbox-group v-model="checkedOptions">-->
<!--              <el-checkbox label="1">A</el-checkbox>-->
<!--              <el-checkbox label="2">B</el-checkbox>-->
<!--              <el-checkbox label="3">C</el-checkbox>-->
<!--              <el-checkbox label="4">D</el-checkbox>-->
<!--            </el-checkbox-group>-->
<!--          </div>-->
          <div v-if="form.type === 1">
            <el-radio-group v-model="form.answer">
              <el-radio v-for="(option, index) in form.options" :key="index" :label="index + 1">{{ getLetter(index) }}</el-radio>
            </el-radio-group>
          </div>
          <div v-if="form.type === 2">
            <el-checkbox-group v-model="checkedOptions">
              <el-checkbox v-for="(option, index) in form.options" :key="index" :label="index + 1">{{ getLetter(index) }}</el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-if="form.type === 3">
            <el-radio-group v-model="form.answer">
              <el-radio label="1">正确</el-radio>
              <el-radio label="0">错误</el-radio>
            </el-radio-group>
          </div>
          <div v-if="form.type === 4">
            <el-input type="textarea" v-model="form.answer" placeholder="请输入参考答案"/>
          </div>
        </el-form-item>
        <el-form-item label="是否公开" prop="isOpen">
          <el-radio-group v-model="form.isOpen">
            <el-radio :label="0">公开</el-radio>
            <el-radio :label="1">不公开</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="难易度" prop="difficulty">
          <el-radio-group v-model="form.difficulty">
            <el-radio
                v-for="dict in question_difficulty"
                :key="dict.value"
                :label="parseInt(dict.value)"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="回答次数" prop="answerTimes">-->
        <!--          <el-input v-model="form.answerTimes" placeholder="请输入回答次数"/>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="回答正确次数" prop="correctTimes">-->
        <!--          <el-input v-model="form.correctTimes" placeholder="请输入回答正确次数"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="分值" prop="score">
          <el-input-number v-model="form.score" :controls-position="right" placeholder="请输入分值"/>
        </el-form-item>
        <el-form-item label="部门id" prop="depId" v-if="false">
          <el-input v-model="form.depId" placeholder="请输入部门id"/>
        </el-form-item>


        <el-form-item label="答案解析" prop="analysis">
          <el-input
              type="textarea"
              v-model="form.analysis"
              placeholder="请输入答案解析"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

  <!-- 题目导入对话框 -->
  <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
    <el-radio-group v-model="upload.uploadType" style="margin-top: 20px;" @change="handleRadioChange">
      <el-radio :label="1">上传文件导入</el-radio>
      <el-radio :label="2">上传图片导入</el-radio>
    </el-radio-group>
    <el-upload
        v-if="upload.uploadType === 1"
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading || upload.isImageUpload"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <template #tip>
        <div class="el-upload__tip text-center">
          <div class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport"/>
            是否更新已经存在的题目数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"
                   @click="importTemplate">下载模板
          </el-link>
        </div>
      </template>
    </el-upload>
    <template v-if="upload.uploadType === 2">
      <MyImgUpload></MyImgUpload>
    </template>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="upload.isUploading">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="Question">
import {addQuestion, delQuestion, getQuestion, listQuestion, updateQuestion} from "@/api/exam/question";
import {listCategory} from '@/api/course/category';
import {addDetail, delDetail, getDetail, updateDetail} from "@/api/exam/detail";
import {getToken} from "@/utils/auth.js";
import MyImgUpload from "@/components/MyImgUpload/index.vue";
import {ElMessage} from "element-plus";

const {proxy} = getCurrentInstance();
const {question_type, question_difficulty} = proxy.useDict('question_type', 'question_difficulty');
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 默认选择上传文件导入
  uploadType: 1,
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: {Authorization: "Bearer " + getToken()},
  // 上传的地址
  url: import.meta.env.VITE_APP_BASE_API + "exam/question/importData"
});
const questionList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const categoryList = ref([]);
const categoryName = ref("");
const checkedOptions = ref([]);
const treeProps = ref({
  value: 'id', // 数据中的 value 字段
  label: 'name', // 数据中的 label 字段
  children: 'children' // 数据中的 children 字段
});
const jsonError = ref(false);
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    type: null,
    difficulty: null,
    courseType: null,
    cateId1: null,
    cateId2: null,
    cateId3: null,
    free: null,
    status: null,
    updateTime: null,
    options: [
      {content: ""},
      {content: ""},
      {content: ""},
      {content: ""}
    ],
    answer: [
      {content: ""},
      {content: ""},
      {content: ""},
      {content: ""}
    ],
    analysis: null,

  },
  /** 通过条件过滤节点  */


  rules: {
    insId: [
      {required: true, message: "机构id不能为空", trigger: "blur"}
    ],
    name: [
      {required: true, message: "题干不能为空", trigger: "blur"}
    ],
    type: [
      {required: true, message: "题目类型不能为空", trigger: "change"}
    ],
    cateId1: [
      {required: true, message: "1级课程分类id不能为空", trigger: "change"}
    ],
    cateId2: [
      {required: true, message: "2级课程分类id不能为空", trigger: "change"}
    ],
    cateId3: [
      {required: true, message: "3级课程分类id不能为空", trigger: "change"}
    ],
    isOpen: [
      {required: true, message: "是否公开不能为空", trigger: "blur"}
    ],
    difficulty: [
      {required: true, message: "难易度不能为空", trigger: "change"}
    ],
    answerTimes: [
      {required: true, message: "回答次数不能为空", trigger: "blur"}
    ],
    correctTimes: [
      {required: true, message: "回答正确次数不能为空", trigger: "blur"}
    ],
    score: [
      {required: true, message: "分值不能为空", trigger: "blur"}
    ],
    createTime: [
      {required: true, message: "创建时间不能为空", trigger: "blur"}
    ],
    updateTime: [
      {required: true, message: "更新时间不能为空", trigger: "blur"}
    ],
    createBy: [
      {required: true, message: "创建人不能为空", trigger: "blur"}
    ],
    updateBy: [
      {required: true, message: "更新人不能为空", trigger: "blur"}
    ]
  }
});

const {queryParams, form, rules} = toRefs(data);
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true;
};

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  upload.open = false;
  upload.isUploading = false;
  proxy.$refs["uploadRef"].handleRemove(file);
  proxy.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", {dangerouslyUseHTMLString: true});
  getList();
};

watch(checkedOptions, (newVal) => {
  data.form.answer = newVal.join(',');
}, {deep: true});

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit();
};

/** 查询题目列表 */
function getList() {
  loading.value = true;
  listQuestion(queryParams.value).then(response => {
    questionList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

function handleImport() {
  upload.title = "题目导入";
  upload.open = true;
};
/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};


// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

function addOption() {
  if (data.form.options.length < 20) { // 假设最多添加10个选项
    data.form.options.push(''); // 添加一个空字符串作为新选项的占位符
  }
}

function deleteOption() {
  if (data.form.options.length > 0) {
    data.form.options.pop(); // 删除最后一个选项
  }
}

const getLetter = (index) => {
  // 'A'.charCodeAt(0) 是字符A的ASCII码，即65
  // index + 65 将索引转换为对应的字母
  return String.fromCharCode(65 + index);
};
/** 下载模板操作 */
function importTemplate() {
  proxy.download("exam/question/importTemplate", {}, `question_template_${new Date().getTime()}.xlsx`);
};

// 表单重置
function reset() {
  form.value = {
    id: null,
    insId: null,
    name: null,
    type: null,
    cateId1: null,
    cateId2: null,
    cateId3: null,
    isOpen: null,
    difficulty: null,
    answerTimes: null,
    correctTimes: null,
    score: null,
    depId: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    options: []
  };
  proxy.resetForm("questionRef");
}

function validateJSON() {
  try {
    JSON.parse(form.options);
    jsonError.value = false;
  } catch (e) {
    jsonError.value = true;
  }
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 节点单击事件 */
function handleNodeClick(data) {
  //重置
  queryParams.value.cateId1 = undefined;
  queryParams.value.cateId2 = undefined;
  queryParams.value.cateId3 = undefined;
  if (data.level === 1) {
    queryParams.value.cateId1 = data.id;
  } else if (data.level === 2) {
    queryParams.value.cateId2 = data.id;
  } else if (data.level === 3) {
    queryParams.value.cateId3 = data.id;
  }
  handleQuery();
}

/** 根据名称筛选分类树 */
watch(categoryName, val => {
  proxy.$refs["categoryTreeRef"].filter(val);
});

/** 查询分类下拉树结构 */
function getCategoryTree() {
  listCategory().then(response => {
    categoryList.value = response.rows;
  });
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.id = undefined;
  proxy.$refs.categoryTreeRef.setCurrentKey(null);
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加题目";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;

  // 使用 Promise.all 来同时处理两个请求
  Promise.all([getQuestion(_id), getDetail(_id)]).then(responses => {
    // 合并两个响应的数据
    const questionData = responses[0].data;
    const detailData = responses[1].data;
    console.log("options", detailData.options)
    console.log("type", questionData.type)
    if (questionData.type === 1 || questionData.type === 2 || questionData.type === 3) {
      detailData.options = JSON.parse(detailData.options);
    }
    // 根据你的需求合并数据
    // 例如，你可以将它们合并到一个对象中，或者更新form.value多次
    form.value = {...form.value, ...questionData, ...detailData};

    // 打开表单
    open.value = true;
    // 设置标题
    title.value = "修改题目";
  }).catch(error => {
    // 处理任何请求中发生的错误
    console.error("Error fetching data: ", error);
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["questionRef"].validate(valid => {
    if (valid) {
      let promises = [];
      let operationType = form.value.id != null ? "修改" : "新增";

      if (form.value.id != null) {
        // 如果有id，表示是更新操作
        promises.push(updateQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
        }).catch(error => {
          console.error("Error updating question: ", error);
        }));
        promises.push(updateDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
        }).catch(error => {
          console.error("Error updating detail: ", error);
        }));
      } else {
        // 如果没有id，表示是新增操作
        promises.push(addQuestion(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
        }).catch(error => {
          console.error("Error adding question: ", error);
        }));
        promises.push(addDetail(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
        }).catch(error => {
          console.error("Error adding detail: ", error);
        }));
      }

      Promise.all(promises).then(() => {
        // 所有操作都完成后，关闭模态框并刷新列表
        open.value = false;
        getList();
        proxy.$modal.msgSuccess(`${operationType}成功`);
      }).catch(error => {
        // 处理任何请求中发生的错误
        console.error("Error during form submission: ", error);
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除题目编号为"' + _ids + '"的数据项？').then(function () {
    // 首先删除题目
    return delQuestion(_ids);
  }).then(function () {
    // 题目删除成功后，删除详情
    return delDetail(_ids);
  }).then(() => {
    // 两个删除操作都完成后，更新列表
    getList();
    // 显示删除成功的消息
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
    // 如果用户取消删除或发生错误，这里可以处理取消逻辑或错误处理
    // 例如，可以显示一个消息提示用户操作已取消或发生错误
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('exam/question/export', {
    ...queryParams.value
  }, `question_${new Date().getTime()}.xlsx`)
}

getCategoryTree();
getList();
</script>
<style scoped>
.option-row {
  margin-bottom: 10px; /* 每行选项之间的间距 */
}

.letter-label {
  margin-right: 10px; /* 字母标签和输入框之间的间距 */
}

.options-input {
  width: 100%;}
</style>
